package se.superduperbudget.superbudgetuser;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import se.superduperbudget.superbudgetuser.user.User;

/**
 *
 * @author olofbjerke
 */
public class LoginServlet extends HttpServlet {

    
    private String targetServlet = "http://home.emilan.se:8084/rs/user/";
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action;
        User user;
        if((action = request.getParameter("action")) != null) {
        
            // Login....
            if(action.equals("login")) {
                
                String name;
                String pass;
                
                if((name = request.getParameter("uname")) != null && 
                        (pass = request.getParameter("pass")) != null) {
                    
                    HttpSession session = request.getSession();
                    if((user = login(name, pass)) != null) {
                        
                        System.out.println("yay");
                        session.setAttribute("user", user);
                        response.sendRedirect("index.xhtml");
                        return;
                    }
                    else {
                        System.out.println("fail med auth");
                        response.sendRedirect("login.xhtml");
                        return;
                        
                        
                    }
                    
                    
                }
                
            }
            // Logout
            else if(action.equals("logout")) {
                System.out.println("logout");
                HttpSession session = request.getSession();
                session.removeAttribute("user");
               
            }
            else if(action.equals("create")) {
                
                String name;
                String pass;
                String pass2;
                
                if((name = request.getParameter("uname")) != null && 
                        (pass = request.getParameter("pass")) != null &&
                        (pass2 = request.getParameter("pass2")) != null &&
                         pass.equals(pass2)) {
                    try {
                        user = new User();
                        
                        user.setUsername(name);
                        user.setPassword(md5ich(pass));
                        user.setFName("");
                        user.setLName("");
                        
                        
                        
                        StringWriter sw  = new StringWriter();
                        
                        JAXBContext jc = JAXBContext.newInstance(User.class);
                        Marshaller m = jc.createMarshaller();
                        m.marshal(user, sw);
                        System.out.println(sw);
                        
                        Client client = Client.create();
                        WebResource web = client.resource("http://home.emilan.se:8084/rs/admin/user");
                       
                        web.type("application/xml").post(sw.toString());
                        
                           
                        response.sendRedirect("index.xhtml");
                        return;
                    } catch (JAXBException ex) {
                        Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                    
                }
                
            }

        }
        else {
            System.out.println("redirect");
            response.sendRedirect("login.xhtml");
            return;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        

        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

/*
    // Skapar en användare
    private User create(String name, String pass) {
        
        return worker(name, pass, "create");
        
    }
  */  
    // Loggar in mot centralen
   private User login(String name, String pass) {
        
       return worker(name, pass, "login");
       
    }
    
    
    private User worker(String name, String pass, String action) {
        
        String params = "username="+name+"&password="+md5ich(pass);
        
        try {
           
            URL url = new URL( targetServlet + action + "?"+params );
            JAXBContext jc = JAXBContext.newInstance(User.class);
            Unmarshaller u = jc.createUnmarshaller();
            User user = (User) u.unmarshal(url);

            if(user == null)
                return null;
            
            // Win
            if(user.getUsername().equals(name) && 
                    user.getPassword().equals(md5ich(pass))) {
                
                return user;
                
            }

        } catch (Exception e) {
                System.out.println(e.toString());
        }

        return null;
        
    }
   
    // Skapar en md5 av en sträng
    private String md5ich(String plaintext) {
        String hashtext = "";
        
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.reset();
            m.update(plaintext.getBytes());
            byte[] digest = m.digest();
            BigInteger bigInt = new BigInteger(1,digest);
            hashtext = bigInt.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while(hashtext.length() < 32 ){
              hashtext = "0"+hashtext;
            }
           
            
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        return hashtext;
    }
}